<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Canvas</title>
</head>

<body>
    <button onclick="drawngray()">黑白图片</button>
    <img src="./syz.jpg" alt="" />
    <canvas id="myCanvas">canvas</canvas>
    <script>
        var drawngray = function () {
            var myCanvas = document.getElementById('myCanvas');
            if (myCanvas.getContext) {
                var context = myCanvas.getContext('2d');
                var image = document.images[0];
                // 动态设置canvas的大小
                myCanvas.width = image.width;
                myCanvas.height = image.height;
                var imageData, data, i, len, average, red, green, blue, alpha;
                //绘制原始图像
                context.drawImage(image, 0, 0);
                //取得图像数据
                imageData = context.getImageData(0, 0, image.width, image.height);
                data = imageData.data;
                for (i = 0, len = data.length; i < len; i += 4) {
                    red = data[i];
                    green = data[i + 1];
                    blue = data[i + 2];
                    // alpha = data[i + 3];
                    //求得 rgb 平均值
                    average = Math.floor((red + green + blue) / 3);
                    //设置颜色值,透明度不变
                    data[i] = average;
                    data[i + 1] = average;
                    data[i + 2] = average;
                }

                //回写图像数据并显示结果
                imageData.data = data;
                context.putImageData(imageData, 0, 0);
            }
        };
    </script>
</body>

</html>